"""
资源管理API
"""

from flask import request, jsonify
from flask_jwt_extended import jwt_required, get_jwt_identity
from app import db
from app.models import Resource, Department, ResourceSchedule, User
from app.api import api_bp

@api_bp.route('/resources', methods=['GET'])
@jwt_required()
def get_resources():
    """获取资源列表"""
    department_id = request.args.get('department_id', type=int)
    resource_type = request.args.get('resource_type')
    
    query = Resource.query
    
    if department_id:
        query = query.filter_by(department_id=department_id)
    if resource_type:
        query = query.filter_by(resource_type=resource_type)
    
    resources = query.all()
    
    result = []
    for resource in resources:
        result.append({
            'id': resource.id,
            'name': resource.name,
            'resource_type': resource.resource_type,
            'department_id': resource.department_id,
            'department_name': resource.department.name,
            'capacity': resource.capacity,
            'status': resource.status,
            'location': resource.location,
            'specifications': resource.specifications
        })
    
    return jsonify(result)

@api_bp.route('/resources/<int:resource_id>', methods=['GET'])
@jwt_required()
def get_resource(resource_id):
    """获取单个资源详情"""
    resource = Resource.query.get(resource_id)
    if not resource:
        return jsonify({'error': '资源不存在'}), 404
    
    # 获取资源排程
    schedules = ResourceSchedule.query.filter_by(resource_id=resource_id).all()
    schedule_list = []
    for schedule in schedules:
        schedule_list.append({
            'id': schedule.id,
            'start_time': schedule.start_time.isoformat(),
            'end_time': schedule.end_time.isoformat(),
            'status': schedule.status,
            'appointment_id': schedule.appointment_id
        })
    
    return jsonify({
        'id': resource.id,
        'name': resource.name,
        'resource_type': resource.resource_type,
        'department_id': resource.department_id,
        'department_name': resource.department.name,
        'capacity': resource.capacity,
        'status': resource.status,
        'location': resource.location,
        'specifications': resource.specifications,
        'schedules': schedule_list
    })

@api_bp.route('/resources', methods=['POST'])
@jwt_required()
def create_resource():
    """创建资源"""
    user_id = get_jwt_identity()
    user = User.query.get(user_id)
    
    # 权限检查
    if user.role != 'admin':
        return jsonify({'error': '无权限操作'}), 403
    
    data = request.get_json()
    
    # 验证必填字段
    required_fields = ['name', 'resource_type', 'department_id']
    for field in required_fields:
        if field not in data:
            return jsonify({'error': f'缺少必填字段: {field}'}), 400
    
    # 验证科室是否存在
    department = Department.query.get(data['department_id'])
    if not department:
        return jsonify({'error': '科室不存在'}), 400
    
    # 创建资源
    resource = Resource(
        name=data['name'],
        resource_type=data['resource_type'],
        department_id=data['department_id'],
        capacity=data.get('capacity', 1),
        location=data.get('location', ''),
        specifications=data.get('specifications', {})
    )
    
    db.session.add(resource)
    db.session.commit()
    
    return jsonify({
        'resource_id': resource.id,
        'message': '资源创建成功'
    }), 201

@api_bp.route('/resources/<int:resource_id>', methods=['PUT'])
@jwt_required()
def update_resource(resource_id):
    """更新资源"""
    user_id = get_jwt_identity()
    user = User.query.get(user_id)
    
    # 权限检查
    if user.role != 'admin':
        return jsonify({'error': '无权限操作'}), 403
    
    resource = Resource.query.get(resource_id)
    if not resource:
        return jsonify({'error': '资源不存在'}), 404
    
    data = request.get_json()
    
    # 更新允许修改的字段
    if 'name' in data:
        resource.name = data['name']
    if 'capacity' in data:
        resource.capacity = data['capacity']
    if 'location' in data:
        resource.location = data['location']
    if 'specifications' in data:
        resource.specifications = data['specifications']
    if 'status' in data:
        resource.status = data['status']
    
    db.session.commit()
    
    return jsonify({'message': '资源更新成功'})

@api_bp.route('/resources/<int:resource_id>/schedule', methods=['POST'])
@jwt_required()
def create_resource_schedule(resource_id):
    """创建资源排程"""
    user_id = get_jwt_identity()
    user = User.query.get(user_id)
    
    # 权限检查
    if user.role not in ['admin', 'doctor']:
        return jsonify({'error': '无权限操作'}), 403
    
    resource = Resource.query.get(resource_id)
    if not resource:
        return jsonify({'error': '资源不存在'}), 404
    
    data = request.get_json()
    
    # 验证必填字段
    required_fields = ['start_time', 'end_time', 'status']
    for field in required_fields:
        if field not in data:
            return jsonify({'error': f'缺少必填字段: {field}'}), 400
    
    # 创建排程
    schedule = ResourceSchedule(
        resource_id=resource_id,
        start_time=datetime.fromisoformat(data['start_time'].replace('Z', '+00:00')),
        end_time=datetime.fromisoformat(data['end_time'].replace('Z', '+00:00')),
        status=data['status'],
        appointment_id=data.get('appointment_id')
    )
    
    db.session.add(schedule)
    db.session.commit()
    
    return jsonify({
        'schedule_id': schedule.id,
        'message': '排程创建成功'
    }), 201

@api_bp.route('/resources/status', methods=['GET'])
@jwt_required()
def get_resource_status():
    """获取资源状态统计"""
    # 统计各类型资源的使用情况
    resource_stats = db.session.query(
        Resource.resource_type,
        Resource.status,
        db.func.count(Resource.id).label('count')
    ).group_by(Resource.resource_type, Resource.status).all()
    
    result = {}
    for resource_type, status, count in resource_stats:
        if resource_type not in result:
            result[resource_type] = {}
        result[resource_type][status] = count
    
    return jsonify(result)

@api_bp.route('/resources/utilization', methods=['GET'])
@jwt_required()
def get_resource_utilization():
    """获取资源利用率"""
    from datetime import datetime, timedelta
    
    # 获取最近7天的数据
    end_date = datetime.now()
    start_date = end_date - timedelta(days=7)
    
    # 计算各资源的利用率
    utilizations = []
    
    resources = Resource.query.all()
    for resource in resources:
        # 计算该资源在指定时间段内的使用时间
        used_time = db.session.query(
            db.func.sum(
                db.func.extract('epoch', ResourceSchedule.end_time - ResourceSchedule.start_time) / 3600
            )
        ).filter(
            ResourceSchedule.resource_id == resource.id,
            ResourceSchedule.start_time >= start_date,
            ResourceSchedule.end_time <= end_date,
            ResourceSchedule.status == 'occupied'
        ).scalar() or 0
        
        # 计算总可用时间（7天 * 8小时）
        total_time = 7 * 8
        utilization = (used_time / total_time) * 100 if total_time > 0 else 0
        
        utilizations.append({
            'resource_id': resource.id,
            'resource_name': resource.name,
            'resource_type': resource.resource_type,
            'utilization': round(utilization, 2)
        })
    
    return jsonify(utilizations)
